package com.tjcd.project.library_base.common.upload.manager;


import com.tjcd.project.library_base.base.network.NetInterceptor;
import com.tjcd.project.library_base.common.basicInfor.SugarUrls;

import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * @Author junweiliu
 * @Description java类作用描述
 * @Version 1.0
 * @CreateDate 2020/6/17
 * @QQ 1007271386
 */
public class FileNetManager {
    // 实例
    public static Retrofit mFileRetrofit;
    // 文件实例
    public static Retrofit mFileProgessRetrofit;

    /**
     * 获取Base
     *
     * @return
     */
    public static Retrofit getBaseFileRetrofit() {
        if (null != mFileRetrofit) {
            return mFileRetrofit;
        }
        mFileRetrofit = getRetrofit();
        return mFileRetrofit;
    }

    /**
     * 获取Retrofit对象
     *
     * @return
     */
    public static Retrofit getRetrofit() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (SugarUrls.DEBUG) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);
        }
//        builder.sslSocketFactory(getSSLSocketFactory(),getX509TrustManager());
        builder.connectTimeout(SugarUrls.FileTimeOut, TimeUnit.SECONDS);
        builder.addInterceptor(new NetInterceptor());
        return new Retrofit.Builder()
                .baseUrl(SugarUrls.DEBUG ? SugarUrls.baseDeBugUrl : SugarUrls.baseUrl)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
    }

    /**
     * 添加带进度
     *
     * @param progress
     * @return
     */
    public static Retrofit getFileRetrofitForProgress(Interceptor progress) {
        if (null != mFileProgessRetrofit) {
            return mFileProgessRetrofit;
        }
        mFileProgessRetrofit = getFileRetrofit(progress);
        return mFileProgessRetrofit;
    }

    /**
     * 获取Retrofit对象
     *
     * @return
     */
    public static Retrofit getFileRetrofit(Interceptor progress) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (SugarUrls.DEBUG) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);
        }
        if (null != progress) {
            builder.addInterceptor(progress);
        }
//        builder.sslSocketFactory(getSSLSocketFactory(),getX509TrustManager());
        builder.connectTimeout(SugarUrls.FileTimeOut, TimeUnit.SECONDS);
        builder.addInterceptor(new NetInterceptor());
        return new Retrofit.Builder()
                .baseUrl(SugarUrls.DEBUG ? SugarUrls.baseDeBugUrl : SugarUrls.baseUrl)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
    }

    // 获取SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 获取TrustManager
    private static TrustManager[] getTrustManager() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    // 获取HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        return (s, sslSession) -> true;
    }

    public static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }


}
